package com.hx.miniblog.util.utils;

/**
 * @author hu wenhao
 * @version 1.0.0
 * @description
 * @date 2022/8/23 21:36
 */

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hx.miniblog.pojo.Weather;
import com.hx.miniblog.pojo.vo.WeatherPhrase;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Supplier;

/**
 * @author cVzhanshi
 * @create 2022-08-04 22:02
 */
public class APIUtils {

    private static final String TIANXING_API_KEY = "47254f11d0d7dd0f23834865d9a2fa88";

    private static final String BAIDU_AK = "3xsGSqej4vGrubYukfGxwecMwOYlEYeh";

    private static final String LOVE_DAY = "2021-10-15";

    private static final String BIRTH_DAY = "2021-04-21";


    public static void main(String[] args) throws ParseException {
        System.out.println("getWeather() = " + getWeather());
//        System.out.println(weatherPhrase("晴"));
//        System.out.println("beautifulPhrase() = " + beautifulPhrase());
//        System.out.println("getLoveDay() = " + getLoveDay());
//        System.out.println("calculationBirthday(BIRTH_DAY) = " + calculationBirthday(BIRTH_DAY));
    }
    public static Weather getWeather(){
        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> map = new HashMap<String,String>();
        map.put("district_id","361002"); // 地方行政代码
        map.put("data_type","all");//这个是数据类型
        map.put("ak",BAIDU_AK);
        String res = restTemplate.getForObject(
                "https://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type={data_type}&ak={ak}",
                String.class,
                map);
        JSONObject json = JSONObject.parseObject(res);
        JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");
        List<Weather> weathers = forecasts.toJavaList(Weather.class);
        JSONObject now = json.getJSONObject("result").getJSONObject("now");
        Weather weather = weathers.get(0);
        weather.setText_now(now.getString("text"));
        weather.setTemp(now.getString("temp"));
        weather.setWind_class(now.getString("wind_class"));
        weather.setWind_dir(now.getString("wind_dir"));
        return weather;
    }

    public static String beautifulPhrase(){
        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> map = new HashMap<String,String>();
        map.put("key",TIANXING_API_KEY);
        String res = restTemplate.getForObject(
                "http://api.tianapi.com/caihongpi/index?key={key}",
                String.class,
                map);

        JSONObject json = JSONObject.parseObject(res);

        JSONArray newslist = JSONObject.parseArray(String.valueOf(json.get("newslist")));

        Map object = newslist.getObject(0, Map.class);

        System.out.println(object.get("content"));

        return object.get("content").toString();

    }

    public static WeatherPhrase weatherPhrase(String tianqi){

        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> map = new HashMap<String,String>();
        map.put("key",TIANXING_API_KEY);
        map.put("tqtype",String.valueOf(getWeatherType(tianqi)));
        String res = restTemplate.getForObject(
                "http://api.tianapi.com/tianqishiju/index?key={key}&tqtype={tqtype}",
                String.class,
                map);

        JSONObject json = JSONObject.parseObject(res);

        JSONArray newslist = JSONObject.parseArray(String.valueOf(json.get("newslist")));

        WeatherPhrase object = newslist.getObject(0, WeatherPhrase.class);

        return object;

    }

    public static Long getLoveDay()   {

        LocalDate from = LocalDate.of(2021, 10, 15);
        long day = LocalDate.now().toEpochDay() - from.toEpochDay();
        System.out.println("距离当前多少日：" + day);
        return day;

    }

    // 计算生日天数
    public static int calculationBirthday(String clidate) throws ParseException {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cToday = Calendar.getInstance(); // 存今天
        Calendar cBirth = Calendar.getInstance(); // 存生日
        cBirth.setTime(myFormatter.parse(clidate)); // 设置生日
        cBirth.set(Calendar.YEAR, cToday.get(Calendar.YEAR)); // 修改为本年
        int days;
        if (cBirth.get(Calendar.DAY_OF_YEAR) < cToday.get(Calendar.DAY_OF_YEAR)) {
            // 生日已经过了，要算明年的了
            days = cToday.getActualMaximum(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
            days += cBirth.get(Calendar.DAY_OF_YEAR);
        } else {
            // 生日还没过
            days = cBirth.get(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
        }
        // 输出结果
        if (days == 0) {
            return 0;
        } else {
            return days;
        }
    }

    public static Map<String,String> collectMessage() throws ParseException {
        Map<String,String> map = new HashMap<>();

        map.put("city","抚州·临川");
        Weather weather = APIUtils.getWeather();
        map.put("weather",weather.getText_now());
        map.put("minTemperature",weather.getLow());
        map.put("maxTemperature",weather.getHigh());
        map.put("weatherPhrase",APIUtils.weatherPhrase(weather.getText_now()).getContent());
        map.put("loveDayCount",APIUtils.getLoveDay().toString());
        map.put("birthdayCount",String.valueOf(APIUtils.calculationBirthday("2021-04-21")));

        return map;
    }

    private static String appId = "wxa892c8e911578671";
    private static String secret = "2aaf4dfb5e82494acd687a359e3a70ca";

    public static void push(Supplier<WxMpTemplateMessage> templateMessageSupplier) throws ParseException {

        //1，配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(appId);
        wxStorage.setSecret(secret);
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        //2,推送消息

        WxMpTemplateMessage templateMessage = templateMessageSupplier.get();

        try {
            System.out.println(templateMessage.toJson());
            System.out.println(wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage));
        } catch (Exception e) {
            System.out.println("推送失败：" + e.getMessage());
            e.printStackTrace();
        }

    }



    public static int getWeatherType(String tianqi){
        int tqtype = 1;

        switch (tianqi){
            case "晴":
                tqtype = 9;
                break;
            case "多云":
                tqtype = 2;
                break;
            case "阴":
                tqtype = 10;
                break;
            case "雾":
                tqtype = 7;
                break;
            case "小雨":
            case "阵雨":
            case "中雨":
            case "大雨":
            case "暴雨":
                tqtype = 3;
                break;
            case "雷阵雨":
                tqtype = 8;
                break;
        }

        return tqtype;
    }
}
